package com.cloudbroker.bcs.platform.dav.middle.util;


import java.util.HashMap;
import java.util.Map;

import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;

/**
 * Created by lnq on 2016/7/26.
 */
public class AppAccessTokenUtil {

    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(AppAccessTokenUtil.class);
    public static String getAppAccessToken(String open_id){
        String userSource = ConfigValues.getUserSource();
        String oauthprovCode = ConfigValues.getOAUTHPROVCODE();
        String app_auth_url= ConfigValues.getAppAuthUrl();
        String app_key = ConfigValues.getAppKey();
        String app_secret = ConfigValues.getAppSecret();
        String keyAndSecret = app_key + ":" + app_secret;
        String authorize = new String(Base64.encode(keyAndSecret.getBytes()));
        Map<String, Object> params = new HashMap<>();
        params.put("open_id", open_id);
        params.put("user_source", userSource);
        params.put("oauthprov_code", oauthprovCode);
        String result = HttpUtil.doPost(app_auth_url,params,HttpUtil.CHARSET,authorize);
        JSONObject obj = JSON.parseObject(result);
        if (obj == null || obj.containsKey("error_code")) {
            return null;
        }
        JSONObject dataObj = JSON.parseObject(obj.getString("data"));
        if (dataObj.get("token") == null) {
            return null;
        }
        String token = dataObj.getString("token");
        return token;
    }
}
